const http = require('http');
const fs = require('fs');
const path = require('path');

// MIME 类型映射
const mimeTypes = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'application/javascript',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.gif': 'image/gif',
  '.json': 'application/json'
};

const server = http.createServer();

server.on('request', (req, res) => {
  console.log('收到客户端请求，路径是：', req.url);

  let fpath = path.join(__dirname, req.url);

  if (req.url === '/') {
    fpath = path.join(__dirname, 'index.html');
  }

  // 获取文件扩展名
  const extname = path.extname(fpath);

  // 设置对应的 Content-Type
  const contentType = mimeTypes[extname] || 'text/plain';
  res.setHeader('Content-Type', contentType);

  fs.readFile(fpath, (err, dataStr) => {
    if (err) {
      res.statusCode = 404;
      res.end('404 Not Found.');
    } else {
      res.end(dataStr);
    }
  });
});

server.listen(8080, () => {
  console.log('服务器启动成功！');
});